/**
 * QUANSHI.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.quanshi.scheduler.core.handler.impl;

import com.quanshi.scheduler.core.base.Ret;
import com.quanshi.scheduler.core.enums.GlueTypeEnum;
import com.quanshi.scheduler.core.executor.IJobExecutor;
import com.quanshi.scheduler.core.handler.IJobHandler;
import com.quanshi.scheduler.core.log.IJobFileAppender;
import com.quanshi.scheduler.core.log.IJobLogger;
import com.quanshi.scheduler.core.utils.ScriptUtils;

/**
 * 
 * 
 * @author chinaxiang
 * @version 2017年7月7日 下午11:45:29
 */
public class ScriptJobHandler implements IJobHandler {

    private long          jobId;
    private long         glueUpdatetime;
    private String       gluesource;
    private GlueTypeEnum glueType;

    public ScriptJobHandler(long jobId, long glueUpdatetime, String gluesource, GlueTypeEnum glueType) {
        this.jobId = jobId;
        this.glueUpdatetime = glueUpdatetime;
        this.gluesource = gluesource;
        this.glueType = glueType;
    }

    public long getGlueUpdatetime() {
        return glueUpdatetime;
    }

    @Override
    public Ret<String> execute(String... params) throws Exception {
        // cmd + script-file-name
        String cmd = "bash";
        String scriptFileName = null;
        if (GlueTypeEnum.GLUE_SHELL == glueType) {
            cmd = "bash";
            scriptFileName = IJobExecutor.logPath.concat("gluesource/").concat(String.valueOf(jobId)).concat("_").concat(String.valueOf(glueUpdatetime)).concat(".sh");
        } else if (GlueTypeEnum.GLUE_PYTHON == glueType) {
            cmd = "python";
            scriptFileName = IJobExecutor.logPath.concat("gluesource/").concat(String.valueOf(jobId)).concat("_").concat(String.valueOf(glueUpdatetime)).concat(".py");
        }

        // make script file
        ScriptUtils.markScriptFile(scriptFileName, gluesource);

        // log file
        String logFileName = IJobExecutor.logPath.concat(IJobFileAppender.contextHolder.get());

        // invoke
        IJobLogger.log("----------- script file:" + scriptFileName + " -----------");
        int exitValue = ScriptUtils.execToFile(cmd, scriptFileName, logFileName, params);
        Ret<String> result = (exitValue == 0) ? Ret.SUCCESS : new Ret<String>(Ret.FAIL_CODE, "script exit value(" + exitValue + ") is failed");
        return result;
    }

}
